package server.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import server.demo.entity.FileData;
import server.demo.service.FileService;
import server.demo.utils.StatusCode;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import static server.demo.utils.StatusCode.*;

@RestController
@RequestMapping("/files")
public class FileController {
    @Autowired
    private FileService fileService;

    /**
     *
     * @param uploadfile
     * @param request
     * @author zq
     * @date 2022/3/1
     */
    @PostMapping(path = "/uploadFile")
    public StatusCode uploadFile(@RequestParam("file") MultipartFile uploadfile, HttpServletRequest request) throws IllegalStateException, IOException {
        // 获取当前时间
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(d);
        String uploadpath = "C:\\data\\"+date;

        // 返回数据
        HashMap<String, Object> map = new HashMap<>();

        // 判断文件是否为空
        if(!uploadfile.isEmpty()){
            File f = new File(uploadpath);
            if(!f.exists()){
                f.mkdir();
            }
            // 保存相关信息
            String id = UUID.randomUUID().toString();
            String fileName = uploadfile.getOriginalFilename();
            Long fileSize = uploadfile.getSize();
            String fileType = uploadfile.getContentType();

            // 转存文件
            String filepath = uploadpath + "\\" + id;
            uploadfile.transferTo(new File(filepath));

            //存入数据库
            FileData file = new FileData();
            file.setUuid(id);
            file.setFname(fileName);
            file.setFtype(fileType);
            file.setFsize(fileSize.toString());
            file.setCreatetime(date);
            file.setLocation(filepath);
            System.out.println("上传文件：");
            System.out.println(file);
            fileService.saveFile(file);


            map.put("uuid",id);  //给客户端传uuid
            return new StatusCode(STATUS_SUCCESS,map);
        }

        // 打印失败信息
        map.put("message","上传失败");
        return new StatusCode(STATUS_FAILURE,map);
    }

    /***
     * 文件下载
     * @param uuid
     * @author zq
     * @date 2022/3/1
     */
    @GetMapping(value = "/downloadFile")
    public StatusCode downloadFile(@RequestParam("ID") String uuid , HttpServletResponse response){
        // 读取数据库中文件信息
        FileData fileDataInfo = fileService.getFileInfo(uuid);
        String date = fileDataInfo.getCreatetime();
        String fileName = fileDataInfo.getFname();
        // 本地保存路径
        String filepath = "C:\\data\\" + date + "\\" +uuid;
        System.out.println(filepath);
        //返回数据
        HashMap<String, Object> map = new HashMap<>();
        // 读到流中
        InputStream inStream = null;
        try {
            inStream = new FileInputStream(filepath);
        } catch (FileNotFoundException e) {
            // 文件不存在
            map.put("error",ERROR);
            map.put("message","文件不存在，请重新输入");
            e.printStackTrace();
            return new StatusCode(STATUS_FAILURE,map);
        }
        // 设置输出的格式
        response.reset();
        response.setContentType("application/json;charset=UTF-8");
        response.addHeader("内容信息", "附件; 文件名=\"" + fileName + "\"");

        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len = 0;
        try {
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            // 关闭流
            inStream.close();
        } catch (IOException e) {
            map.put("error",ERROR);
            map.put("message","下载失败");
            e.printStackTrace();
            return new StatusCode(STATUS_FAILURE,map);
        }
        return new StatusCode(STATUS_SUCCESS);
    }
    /**
     * @author zq
     * @date 2022/3/1
     * */
    @GetMapping(value = "/FileInfo")
    public StatusCode getFileInfo(@RequestParam("ID") String uuid){
        FileData fileDataInfo = fileService.getFileInfo(uuid);
        return new StatusCode(fileDataInfo);
    }
}
